<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="出库编号" prop="shipmentsCode">
        <el-input v-model="queryParams.shipmentsCode" placeholder="请输入出库编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="出库时间" prop="shipmentsDate">
        <el-date-picker clearable
          v-model="queryParams.shipmentsDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择出库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="开始编号" prop="starCode">
        <el-input
          v-model="queryParams.starCode"
          placeholder="请输入开始编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结束编号" prop="endCode">
        <el-input
          v-model="queryParams.endCode"
          placeholder="请输入结束编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="代理商编号" prop="agentCode">
        <el-input v-model="queryParams.agentCode" placeholder="请输入代理商编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="数量" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位" prop="shipmentsUnit">
        <el-input
          v-model="queryParams.shipmentsUnit"
          placeholder="请输入单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['shipments:shipments:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['shipments:shipments:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['shipments:shipments:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['shipments:shipments:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shipmentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="出库Id" align="center" prop="shipmentsId" /> -->
      <el-table-column label="出库编号" align="center" prop="shipmentsCode" />
      <el-table-column label="出库时间" align="center" prop="shipmentsDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.shipmentsDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始编号" align="center" prop="starCode" />
      <el-table-column label="结束编号" align="center" prop="endCode" />
      <el-table-column label="代理商编号" align="center" prop="agentCode" />
      <el-table-column label="代理商名称" align="center" prop="agentName" />
      <el-table-column label="数量" align="center" prop="number" />
      <el-table-column label="单位" align="center" prop="shipmentsUnit" />
      <el-table-column label="产品编号" align="center" prop="materialCode" />
      <el-table-column label="产品名称" align="center" prop="materialName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['shipments:shipments:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['shipments:shipments:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改出库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出库编号" prop="shipmentsCode">
          <el-input v-model="form.shipmentsCode" placeholder="请输入出库编号" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出库时间" prop="shipmentsDate">
              <el-date-picker clearable v-model="form.shipmentsDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择出库时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="number">
              <el-input v-model="form.number" placeholder="0" id="numberInput" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="开始编号" prop="starCode">
          <el-input v-model="form.starCode" placeholder="请输入开始编号（编号格式为：前缀加_数值字符 OR 存数值字符）" id="startCodeInput"
            @keyup.native="Addsum()" />
        </el-form-item>
        <el-form-item label="结束编号" prop="endCode">
          <el-input v-model="form.endCode" placeholder="请输入结束编号（编号格式为：前缀加_数值字符 OR 存数值字符）" id="endCodeInput"
            @keyup.native="Addsum()" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="代理商" prop="agentName">
              <el-select v-model="form.agentName" placeholder="请选择代理商">
                <el-option 
                v-for="item in agentNames" 
                :key="item.agentId" 
                :label="item.agentName"
                :value="item.agentId" 
                :disabled="item.status == 1">
              </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-form-item label="代理商编号" prop="agentCode" label-width="90px">
          <el-input v-model="form.agentCode" placeholder="请输入代理商编号" />
        </el-form-item> -->
          <el-col :span="12" >
            <el-form-item label ="产品名称" prop="materialName">
            <el-select v-model=" form.materialName " placeholder="请选择产品名称">
              <el-option 
              v-for=" item  in  materialNames " 
              :key=" item.materialId " 
              :label=" item.materialName "
              :value=" item.materialId " 
              :disabled=" item.status == 1 ">
            </el-option>
            </el-select>
            </el-form-item>
            <!-- <el-form-item label="产品编号" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入产品编号" />
        </el-form-item> -->
            <!-- <el-form-item label="产品名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入产品名称" />
        </el-form-item> -->
          </el-col>
          <el-col :span="12" >
            <el-form-item label ="单位" prop="shipmentsUnit">
            <el-select v-model=" form.shipmentsUnit " placeholder="请选择单位">
              <el-option v-for=" item  in  shipmentsUnits " :key=" item.unitId " :label=" item.unitName "
                :value=" item.unitId " :disabled=" item.status == 1 "></el-option>
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="单位" prop="shipmentsUnit">
          <el-input v-model="form.shipmentsUnit" placeholder="请输入单位" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click=" submitForm ">确 定</el-button>
        <el-button @click=" cancel ">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listShipments, getShipments, delShipments, addShipments, updateShipments } from "@/api/shipments/shipments";

export default {
  name: "Shipments",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库表格数据
      shipmentsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shipmentsCode: null,
        shipmentsDate: null,
        starCode: null,
        endCode: null,
        agentCode: null,
        agentName: null,
        number: null,
        shipmentsUnit: null,
        materialCode: null,
        materialName: null
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        shipmentsCode: [
          { required: true, message: "出库编号不能为空", trigger: "blur"},
          { min: 3, max: 20, message: '出库编号必须介于3 和 20之间', trigger: 'blur'}
        ],
        starCode: [
          { required: true, message: "开始编号不能为空", trigger: "blur"},
          { min: 3, max: 20, message: '开始编号必须介于3 和 20之间', trigger: 'blur'}
        ],
        endCode: [
          { required: true, message: "结束编号不能为空", trigger: "blur"},
          { min: 3, max: 20, message: '结束编号必须介于3 和 20之间', trigger: 'blur'}
        ],
        agentName: [
          { required: true, message: "代理商不能为空", trigger: "blur"},
        ],
        materialName: [
          { required: true, message: "产品不能为空", trigger: "blur"},
        ],
        shipmentsUnit: [
          { required: true, message: "产品单位不能为空", trigger: "blur"},
        ],
        shipmentsDate: [
          { required: true, message: "出库时间不能为空", trigger: "blur"},
        ],
      },
      // 代理商集合
      agentNames: [],
      // 产品集合
      materialNames: [],
      // 单位集合
      shipmentsUnits: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {

    Addsum() {
      // 获取输入框的值
      var startCodeString = "";
      var endCodeString = "";
      var floatStartCode = 0;
      var floatEndCode = 0;
      var startCodeMath = document.getElementById("startCodeInput").value; //获取开始编号input框value值
      var endCodeMath = document.getElementById("endCodeInput").value; //获取结束编号input框value值

      if ((!isNaN(parseFloat(startCodeMath)) && isFinite(startCodeMath)) && (!isNaN(parseFloat(endCodeMath)) && isFinite(endCodeMath))) {
        var sum = parseFloat(endCodeMath) - parseFloat(startCodeMath);
        this.form.number = sum;
        document.getElementById("numberInput").value = sum; //赋值给总数量的input框
      } else {
        var startIndex = startCodeMath.indexOf("_");
        var endIndex = endCodeMath.indexOf("_");
        if (startIndex >= 1 && endIndex >= 1) {
          startCodeString = startCodeMath.substring(startIndex + 1, startCodeMath.length);
          endCodeString = endCodeMath.substring(endIndex + 1, endCodeMath.length);
        }
        // if(endIndex >= 1){
        //   endCodeString = endCodeMath.substring(endIndex + 1,endCodeMath.length);
        // }
        if (!isNaN(parseFloat(startCodeString)) && isFinite(startCodeString)) {
          if (startCodeString != "") {
            floatStartCode = parseFloat(startCodeString);
          }
        }
        if (!isNaN(parseFloat(endCodeString)) && isFinite(endCodeString)) {
          if (endCodeString != "") {
            floatEndCode = parseFloat(endCodeString);
          }
        }
        //合计数量
        var sum = floatEndCode - floatStartCode;
        this.form.number = sum;
        //只读框赋值（总数量）
        document.getElementById("numberInput").value = sum; //赋值给总数量的input框
      }
    },
    /** 查询出库列表 */
    getList() {
      this.loading = true;
      listShipments(this.queryParams).then(response => {
        this.shipmentsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        shipmentsId: null,
        shipmentsCode: null,
        shipmentsDate: null,
        starCode: null,
        endCode: null,
        agentCode: null,
        agentName: null,
        number: null,
        shipmentsUnit: null,
        materialCode: null,
        materialName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.shipmentsId)
      this.codes = selection.map(item => item.shipmentsCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getShipments().then(response => {
        this.agentNames = response.agentNames;
        this.materialNames = response.materialNames;
        this.shipmentsUnits = response.shipmentsUnits;
        this.open = true;
        this.title = "添加出库";
        if(document.getElementById("numberInput") !== null){
          document.getElementById("numberInput").value = 0; //赋值给总数量的input框
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const shipmentsId = row.shipmentsId || this.ids
      getShipments(shipmentsId).then(response => {
        this.form = response.data;
        this.agentNames = response.agentNames;
        this.materialNames = response.materialNames;
        this.shipmentsUnits = response.shipmentsUnits;
        this.open = true;
        this.title = "修改出库";
        if(document.getElementById("numberInput") !== null){
          document.getElementById("numberInput").value = 0; //赋值给总数量的input框
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.shipmentsId != null) {
            updateShipments(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.number === null || this.form.number <= 0) {
              this.$modal.msgError("请填写正确的开始编号和结束编号计算出数量");
              return;
            }
            addShipments(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const shipmentsIds = row.shipmentsId || this.ids;
      const shipmentsCodes = row.shipmentsCode || this.codes;
      this.$modal.confirm('是否确认删除出库编号为"' + shipmentsCodes + '"的数据项？').then(function () {
        return delShipments(shipmentsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('shipments/shipments/export', {
        ...this.queryParams
      }, `shipments_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
